﻿/*
    a04_Event @ https://gitee.com/zcatt/MyDemo2020

event是一种特殊的delegate. 籍此很容易实现publisher-subscriber或observer模式.
实际使用中通常需要子类EventArgs以承载额外的信息.
 
*/
using System;

public class Publisher
{
    public event EventHandler m_changed;

    protected virtual void onChanged(EventArgs e)
    {
        if (m_changed != null)
            m_changed(this, e);
    }

    public void doSomeThing()
    {
        //do actions

        onChanged(EventArgs.Empty);
    }
}

public class Subscriber
{
    private Publisher m_publisher;
    private string m_name;

    public Subscriber(string name)
    {
        m_name = name;
    }

    public void subscribe(Publisher publisher)
    {
        m_publisher = publisher;
        m_publisher.m_changed += new EventHandler(changedCallback);
    }

    public void unsubscribe()
    {
        m_publisher.m_changed -= new EventHandler(changedCallback);
        m_publisher = null;

    }

    private void changedCallback(object sender, EventArgs e)
    {
        Console.WriteLine("{0} received changed callback", m_name);
    }

}

class Program
{
    static void Main(string[] args)
    {
        Publisher p = new Publisher();
        Subscriber s1 = new Subscriber("s1");
        Subscriber s2 = new Subscriber("s2");

        s1.subscribe(p);
        s2.subscribe(p);

        Console.WriteLine("do 1");
        p.doSomeThing();

        s1.unsubscribe();

        Console.WriteLine("do 2");
        p.doSomeThing();

        s2.unsubscribe();

        Console.WriteLine("do 3");    
        p.doSomeThing();

        return;
    }

}
